import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {PERMISSION, formatExportExcelUrl, formatExportPdfUrl} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH, DATE_FORMAT} from '../constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {marketingActivityStatus, currency} from '../Enum';
import {abandonData, submitData} from './api';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickSubmitBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        submitData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onExportExcel = e => {
        e.stopPropagation();
        window.open(formatExportExcelUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    onExportPdf = e => {
        e.stopPropagation();
        window.open(formatExportPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [
            {
                title: formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '活动编号'
                }),
                dataIndex: 'code',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)}>{record.code}</Link>
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.name',
                    defaultMessage: '活动名称'
                }),
                dataIndex: 'name',
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.dealerName',
                    defaultMessage: '总代名称'
                }),
                dataIndex: 'dealerName',
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country',
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.marketDepartmentName',
                    defaultMessage: '大区名称'
                }),
                dataIndex: 'marketDepartmentName',
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.totalInvestAmount',
                    defaultMessage: '投入总金额'
                }),
                dataIndex: 'totalInvestAmount',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.totalSupportAmount',
                    defaultMessage: '支持总金额'
                }),
                dataIndex: 'totalSupportAmount',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.totalSupportRatio',
                    defaultMessage: '支持总比例'
                }),
                dataIndex: 'totalSupportRatio',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.startDate',
                    defaultMessage: '活动开始日期'
                }),
                dataIndex: 'startDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.endDate',
                    defaultMessage: '活动结束日期'
                }),
                dataIndex: 'endDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(marketingActivityStatus, text)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.operate',
                    defaultMessage: '操作'
                }),
                dataIndex: 'operate',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.id)}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '修改'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.abandon,
                            children: (ref =>
                                <WrappedPopconfirm
                                    key="abandon"
                                    placement="topLeft"
                                    onConfirm={this.onClickAbandonBtn}
                                    onVisibleChange={ref.setMenuVisible}
                                    id={r.id}
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.validate.abandon',
                                        defaultMessage: '是否确认作废？'
                                    })}>
                                    <a>{
                                        this.props.intl.formatMessage({
                                            id: 'tablePanel.abandon',
                                            defaultMessage: '作废'
                                        })
                                    }</a>
                                </WrappedPopconfirm>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                        },
                        {
                            id: PERMISSION.submit,
                            children: (ref =>
                                <WrappedPopconfirm
                                    key="submit"
                                    placement="topLeft"
                                    onConfirm={this.onClickSubmitBtn}
                                    onVisibleChange={ref.setMenuVisible}
                                    id={r.id}
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.validate.submit',
                                        defaultMessage: '是否确认提交？'
                                    })}>
                                    <a>{
                                        this.props.intl.formatMessage({
                                            id: 'tablePanel.submit',
                                            defaultMessage: '提交'
                                        })
                                    }</a>
                                </WrappedPopconfirm>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit)),
                        }, {
                            id: PERMISSION.upload,
                            children: (
                                <Link key="upload" to={routes.upload.format(r.id)}>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.upload',
                                        defaultMessage: '上传报告和发票'
                                    })
                                }</Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.upload) && hasPermissions(r.options, PERMISSION.upload)),
                        }, {
                            id: PERMISSION.register,
                            children: (
                                <Link key="register" to={routes.register.format(r.id)}>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.register',
                                        defaultMessage: '登记核销结果'
                                    })
                                }</Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.register) && hasPermissions(r.options, PERMISSION.register)),
                        }, {
                            id: PERMISSION.approve,
                            children: (
                                <Link key="approve" to={routes.approve.format(r.id)}>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.approve',
                                        defaultMessage: '审核'
                                    })
                                }</Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve)),
                        }, {
                            id: PERMISSION.approveReport,
                            children: (
                                <Link key="approveReport" to={routes.approveReport.format(r.id)}>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.approveReport',
                                        defaultMessage: '审核报告和发票'
                                    })
                                }</Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.approveReport) && hasPermissions(r.options, PERMISSION.approveReport)),
                        },
                        {
                            id: PERMISSION.approveFee,
                            children: (
                                <Link key="approveFee" to={routes.approveFee.format(r.id)}>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.approveFee',
                                        defaultMessage: '审核发票和费用'
                                    })
                                }</Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.approveFee) && hasPermissions(r.options, PERMISSION.approveFee)),
                        }, {
                            id: PERMISSION.exportExcel,
                            children: (
                                <a key="exportExcel" data-id={r.id} data-code={r.code} onClick={this.onExportExcel}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.exportExcel',
                                        defaultMessage: '导出Excel'
                                    })}
                                </a>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.exportExcel) && hasPermissions(r.options, PERMISSION.exportExcel))
                        }, {
                            id: PERMISSION.exportPdf,
                            children: (
                                <a key="exportPdf" data-id={r.id} data-code={r.code} onClick={this.onExportPdf}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.exportPdf',
                                        defaultMessage: '导出PDF'
                                    })}
                                </a>
                            ),
                            hidden: !hasPermissions(this.props.permissions, PERMISSION.exportPdf)
                        }];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }];
        return (
            <Table
                className={'white-space-nowrap'}
                columns={columns}
                dataSource={this.props.data}
                loading={this.props.loading || this.state.loading}
                onChange={this.onChangeSort}
                pagination={pagination}
                rowKey="id"
                locale={locale}
                {...TABLE}/>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getIsDealerUser = selectorFactory(['page', 'domainData', 'initData', 'isDealerUser']);
const mapStateToProps = state => ({
    data: getData(state),
    isDealerUser: getIsDealerUser(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


